package activity.order;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.itboye.hutoubenjg.R;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import base.MyApplcation;
import fragment.IndexFragment;
import util.utls.CameraPopupWindowmap;
import util.utls.IsUtilUid;
import util.utls.UIAlertView;

import static android.R.attr.radius;
import static java.lang.Double.parseDouble;

public class MapActivity extends Activity {
    private LocationClient locationClient;//定位客户�?
    private MapView mvMap;//百度地图控件
    private BaiduMap baiduMap;
    private Button btnMaps;//地图对象控制�?
    //    private ZoomControlsView zcvZomm;//缩放控件
    private static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    Button btnMap;
    TextView tvPhone;
    CameraPopupWindowmap cameraPopupWindow;

    String mobile="", addres="";
    UIAlertView uiAlertView;
    String lat="", lng="";
    private final int BAIDU_READ_PHONE_STATE = 127;
    double[] gaode;//百度地图转化的高德地图坐标

    private MyLocationData locData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //必须在setContentView�?
        setContentView(R.layout.map_activity);

        initMap();
        initLocation();
        getPersimmions();
    }

    /*
     *判断当前是否是6.0版本
     */
    private void getPersimmions() {
        // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            isCameraPermission(this, 1);
            //     requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE + "", Manifest.permission.ACCESS_COARSE_LOCATION + "", Manifest.permission.ACCESS_FINE_LOCATION + "", Manifest.permission.READ_EXTERNAL_STORAGE + "", Manifest.permission.WRITE_EXTERNAL_STORAGE + ""}, BAIDU_READ_PHONE_STATE);
        } else {
            initMap();
        }
    }

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    public static boolean isCameraPermission(Activity context, int requestCode) {
        if (Build.VERSION.SDK_INT >= 23) {
            int aPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
            int bPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            int cPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
            int dPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int ePermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (aPermission != PackageManager.PERMISSION_GRANTED || bPermission != PackageManager.PERMISSION_GRANTED || cPermission != PackageManager.PERMISSION_GRANTED || dPermission != PackageManager.PERMISSION_GRANTED || ePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, PERMISSIONS, requestCode);
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    initMap();
                } else {
                    // 没有获取到权限，做特殊处理
                }
                break;
            default:
                break;
        }
    }

    /**
     * 初始化地�?
     */
    private void initMap() {
        //获取地图控件
        mvMap = (MapView) findViewById(R.id.mv_map);
        btnMap = (Button) findViewById(R.id.btnMap);
        btnMaps = (Button) findViewById(R.id.btnMaps);
        mvMap.showZoomControls(false);//隐藏缩放控件
        //获取地图对象控制�?
        baiduMap = mvMap.getMap();
        baiduMap.setBuildingsEnabled(true);//设置显示楼体
        baiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(19f));//设置地图状�??

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000;
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        addres = getIntent().getStringExtra("addres");
        mobile = getIntent().getStringExtra("mobile");
        lat = getIntent().getStringExtra("lat");
        lng = getIntent().getStringExtra("lng");
        baiduMap = mvMap.getMap();
        Log.d("getIntent", lng + "");
        tvPhone.setText("司机电话:" + mobile);

        gaode = bdToGaoDe(Double.parseDouble(lat), Double.parseDouble(lng));

        btnMaps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //用intent启动拨打电话
                showDelDialog(mobile);

            }
        });
        btnMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                cameraPopupWindow = new CameraPopupWindowmap(
                        MapActivity.this, onclicklister);
                cameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);

            }
        });

    }

    private View.OnClickListener onclicklister = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            switch (view.getId()) {
                case R.id.open_camera:
                    onBaidu();
                    cameraPopupWindow.dismiss();
                    break;
                case R.id.pick_image:
                    onGoade();
                    cameraPopupWindow.dismiss();
                    break;
                case R.id.pick_guge:
                    onGuge();
                    cameraPopupWindow.dismiss();
                    break;
            }
        }
    };

    /**
     * 百度地图坐标转高德地图
     * @param bd_lat
     * @param bd_lon
     * @return
     */
    private double[] bdToGaoDe(double bd_lat, double bd_lon) {
        double[] gd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        gd_lat_lon[0] = z * Math.cos(theta);
        gd_lat_lon[1] = z * Math.sin(theta);
        return gd_lat_lon;
    }


    /***
     * 高德地图
     */
    public void onGoade() {
        double[] g = bdToGaoDe(IndexFragment.lat, IndexFragment.lng);

        if (isInstallByread("com.autonavi.minimap")) {
            try {
                String s = "androidamap://route?sourceApplication=amap&slat=" + g[1] + "&slon=" + g[0] + "&sname=abc&dlat=" + gaode[1] + "&dlon=" + gaode[0] + "&dname=def&dev=0&t=2";
                Log.d("RRRRR", g[1] + "" + g[0] + "" + gaode[1] + "" + gaode[0] + "");
                String ss = "androidamap://route?sourceApplication=amap&dlat=" + gaode[1] + "&dlon=" + gaode[0] + "&dname=" + addres+ "&dev=0&t=2";
                //Intent intent = Intent.getIntent(ss);
                Intent intent = Intent.getIntent("androidamap://navi?sourceApplication=" + IsUtilUid.isAdd() + "&poiname=我的目的地&lat=" + gaode[1] + "&lon=" + gaode[0] + "&dev=0"+ "&style=2");
                startActivity(intent);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(MyApplcation.ctx, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
            Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }

    /***
     * 百度地图
     */
    public void onBaidu() {
        if (isAvilible(MapActivity.this, "com.baidu.BaiduMap")) {
            try {
                // Intent intent = Intent.getIntent("intent://map/direction?origin=latlng:" + lat + "," + lng + "|name:" + IsUtilUid.isAdd() + "+destination=" + IsUtilUid.isAdd() + "&mode=driving®ion=" + IsUtilUid.isAdd() + "&referer=Autohome|GasStation#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                Intent intent = Intent.getIntent("intent://map/direction?" +
                        //"origin=latlng:"+"34.264642646862,108.95108518068&" +   //起点  此处不传值默认选择当前位置
                        "destination=latlng:" + lat + "," + lng + "|name:我的目的地" +        //终点
                        "&mode=driving&" +          //导航路线方式
                        //    "region=上海" +
                        "&src=虎头奔#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                startActivity(intent); //启动调用
            } catch (URISyntaxException e) {
                Log.e("intent", e.getMessage());
            }
        } else {//未安装
            //market为路径，id为包名
            //显示手机上所有的market商店
            Toast.makeText(MapActivity.this, "您尚未安装百度地图", Toast.LENGTH_LONG).show();
            Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }


    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param context
     * @param packageName 应用包名
     * @return
     */
    public static boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }


    /***
     * 谷歌地图
     */
    public void onGuge() {
        if (isInstallByread("com.google.android.apps.maps")) {
            Uri gmmIntentUri = Uri.parse("google.navigation:q=" + lat + "," + lng + ", + Sydney +Australia");
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
            mapIntent.setPackage("com.google.android.apps.maps");
            startActivity(mapIntent);
        } else {
            Toast.makeText(MyApplcation.ctx, "您尚未安装谷歌地图", Toast.LENGTH_LONG).show();

            Uri uri = Uri.parse("market://details?id=com.google.android.apps.maps");
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }

    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    private void initLocation() {
        // TODO Auto-generated method stub
        // -----------location config ------------
        System.out.println("lng" + lng + "lat" + lat);
        locData = new MyLocationData.Builder().accuracy(radius).direction(100)
                .latitude(parseDouble(lat)).longitude(parseDouble(lng)).build();
        // // 此处设置开发者获取到的方向信息，顺时针0-360
        baiduMap.setMyLocationData(locData); // 设置定位数据
        LatLng ll = new LatLng(parseDouble(lat), parseDouble(lng));
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 16); // 设置地图中心点以及缩放级别
        baiduMap.animateMapStatus(u);
        TextView textView = new TextView(MyApplcation.ctx);
        textView.setText("自定义的覆盖物");
        textView.setTextSize(16);
        // 将View转换为BitmapDescriptor
        BitmapDescriptor descriptor = BitmapDescriptorFactory
                .fromBitmap(BitmapFactory.decodeResource(getResources(),
                        R.drawable.weizhi));
        // 设置覆盖物属性，位置、标题、图标。。。
        MarkerOptions markerOptions = new MarkerOptions()
                .position(new LatLng(parseDouble(lat), parseDouble(lng))).icon(descriptor).title("标题")
                .zIndex(9).draggable(true);
        // 在地图上添加覆盖物
        mvMap.getMap().addOverlay(markerOptions);
    }


    @Override
    protected void onPause() {
        super.onPause();
        mvMap.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mvMap.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != locationClient && locationClient.isStarted()) {
            locationClient.stop();//停止定位
        }
        locationClient = null;
        try {
            mvMap.onDestroy();
        } catch (Exception e) {

        }
    }


    private void showDelDialog(final String phoneNumber) {
        uiAlertView = new UIAlertView(MapActivity.this, "温馨提示！", "是否拨打电话\n" + phoneNumber, "否", "是");
        uiAlertView.show();

        uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {

            public void doLeft() {
                uiAlertView.dismiss();
            }

            public void doRight() {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
                if (ActivityCompat.checkSelfPermission(MapActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                startActivity(intent);
//                System.exit(0);
            }
        });
    }

}
